import { Injectable } from '@nestjs/common';
import { User } from './user.entity'; // Assuming you have a User entity defined
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, Like } from 'typeorm'
import { CreateUserDto } from './create-user-dto'
import { v4 as uuidv4 } from 'uuid';
import * as md5 from 'md5';
import { wrapperResponse } from '../utils/index';

@Injectable()
export class UserService {
    constructor(@InjectRepository(User) private readonly userRepository: Repository<User>) { }

    // 创建用户
    create(CreateUserDto: CreateUserDto): Promise<User> {
        CreateUserDto.userId = uuidv4()
        // CreateUserDto.deptId = uuidv4()
        CreateUserDto.userPwd = md5(CreateUserDto.userPwd).toUpperCase()

        return this.userRepository.save(CreateUserDto);
    }

    // 更新用户
    async update(updateUserDto: Partial<CreateUserDto>): Promise<User> {
        const user = await this.userRepository.findOneBy({ userId: updateUserDto.userId });

        // 更新用户数据
        Object.assign(user, CreateUserDto);

        // 保存更新后的用户
        return wrapperResponse(this.userRepository.save(updateUserDto), '更新用户成功');
    }

    // 查找某一个用户
    findByUsername(userName: string): Promise<User> {
        return this.userRepository.findOneBy({ userName })
    }

    // 获取用户列表
    findUserList(params) {
        let { pageNum, pageSize, userId, userName, state } = params
        pageNum = pageNum || 1;
        pageSize = pageSize || 10;
        const whereCondition: any = {};

        if (userId) {
            whereCondition.userId = Like(`%${userId.trim()}%`);
        }

        // 如果传入了 author，则添加 author 的模糊查询条件
        if (userName) {
            whereCondition.userName = Like(`%${userName.trim()}%`);
        }

        if (state) {
            whereCondition.state = Like(`%${state}%`);
        }

        return this.userRepository.findAndCount({
            where: whereCondition,
            take: pageSize,
            skip: Number((pageNum - 1) * pageSize),
            order: {
                id: 'DESC'
            }
        }).then(res => {
            const [list, total] = res
            return Promise.resolve({ list, page: { total } })
        })
    }

    // 批量删除用户
    batchRemoveUser(id) {
        const uid = id.split(',')
        return Promise.all(uid.map(userId => {
            return this.userRepository.delete(userId);
        }))
            .then(() => {
                return Promise.resolve();
            })
            .catch((error) => {
                throw new Error(`Failed to delete users: ${error.message}`);
            });
    }

}
